﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Centido.Core.Dto;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Centido.Core.Test
{
    /// <summary>
    ///   Testing the data transfer object for an enumeration column.
    /// </summary>
    [TestClass]
    public class EnumColumnDtoTest : GenericDtoTest
    {
        /// <summary>
        ///   The current domain name.
        /// </summary>
        public const string DomainName = "FullAdminRights";

        /// <summary>
        ///   The current domain.
        /// </summary>
        private Domain _domain;

        /// <summary>
        ///   The table.
        /// </summary>
        private Table _table;

        /// <summary>
        ///   The enumeration column.
        /// </summary>
        private EnumColumn _enumColumn;

        /// <summary>
        /// Test initialiaze
        /// </summary>
        [TestInitialize]
        public void Initialize()
        {
            _domain = Domain.Build(DomainConfiguration.Load(DomainName));

            _domain.DeleteAll();

            _table = _domain.AddTable(StringProperty.RandomIdentifier());

            _enumColumn = EnumColumn.Add(_table, StringProperty.RandomIdentifier());

            _enumColumn.AddMember(1);
        }

        /// <summary>
        /// Test clean up
        /// </summary>
        [TestCleanup]
        public void CleanUp()
        {
            _domain.DeleteAll();
        }


        /// <summary>
        ///   Retrieves the name of the data transfer object xml tag.
        /// </summary>
        /// <returns></returns>
        protected override string GetXmlTag()
        {
            return EnumColumnDto.XmlTag;
        }

        /// <summary>
        ///   Retrives the current xml schema version.
        /// </summary>
        /// <returns></returns>
        protected override string GetCurrentXmlSchemaVersion()
        {
            return EnumColumnDto.CurrentXmlSchemaVersion;
        }

        /// <summary>
        ///   Creates a new data transfer object.
        /// </summary>
        /// <returns></returns>
        protected override DataTransferObject CreateDto()
        {
            return new EnumColumnDto
            {
                Name = StringProperty.RandomIdentifier().ToLower(),
                DisplayName = StringProperty.StandardValue('a'),
                Description = StringProperty.ExtendedValue('a'),
                IsNotNull = new Random(Environment.TickCount).Next() % 2 == 0,
                OrderIndex = new Random(Environment.TickCount).Next(),
                HasValueChecking = new Random(Environment.TickCount).Next() % 2 == 0,
                DefaultValue = 1
            };
        }

        /// <summary>
        ///   Retrieves the list of data transfer object fields.
        /// </summary>
        /// <returns></returns>
        protected override IEnumerable<DtoFieldInfo> GetFields()
        {
            yield return new DtoFieldInfo
            {
                Name = "Name",
                XmlName = ColumnDto.NameAttribute,
                IsRequired = true,
                FieldType = DtoFieldType.String,
                SampleValue = StringProperty.RandomIdentifier()
            };
            yield return new DtoFieldInfo
            {
                Name = "DisplayName",
                XmlName = ColumnDto.DisplayNameAttribute,
                IsRequired = false,
                FieldType = DtoFieldType.String,
                SampleValue = StringProperty.StandardValue('a')
            };
            yield return new DtoFieldInfo
            {
                Name = "Description",
                XmlName = ColumnDto.DescriptionAttribute,
                IsRequired = false,
                FieldType = DtoFieldType.String,
                SampleValue = StringProperty.ExtendedValue('a')
            };
            yield return new DtoFieldInfo
            {
                Name = "OrderIndex",
                XmlName = ColumnDto.OrderIndexAttribute,
                IsRequired = false,
                FieldType = DtoFieldType.Integer,
                SampleValue = 7
            };
            yield return new DtoFieldInfo
            {
                Name = "IsNotNull",
                XmlName = ColumnDto.IsNotNullAttribute,
                IsRequired = false,
                FieldType = DtoFieldType.Boolean,
                SampleValue = true
            };
            yield return new DtoFieldInfo
            {
                Name = "DefaultValue",
                XmlName = EnumColumnDto.DefaultValueAttribute,
                IsRequired = false,
                FieldType = DtoFieldType.Integer,
                SampleValue = 5
            };
            yield return new DtoFieldInfo
            {
                Name = "HasValueChecking",
                XmlName = EnumColumnDto.HasValueCheckingAttribute,
                IsRequired = false,
                FieldType = DtoFieldType.Boolean,
                SampleValue = true
            };
        }

        /// <summary>
        ///   Copies the properties of the data transfer object to the corresponding object.
        /// </summary>
        /// <param name="dto">The data transfer object.</param>
        /// <returns>Returns the corresponding object after copying.</returns>
        protected override object CopyFrom(DataTransferObject dto)
        {
            ((EnumColumnDto)dto).CopyTo(_enumColumn);

            return _enumColumn;
        }

        /// <summary>
        ///   Creates a data transfer object from the correpsonding object.
        /// </summary>
        /// <param name="dto">The created data transfer object.</param>
        /// <param name="initialObject">The initial object.</param>
        protected override void CreateDtoFromObject(out DataTransferObject dto, out object initialObject)
        {
            dto = EnumColumnDto.CreateFrom(_enumColumn);
            initialObject = _enumColumn;
        }


        /// <summary>
        ///   Reading the enumeration column member list from xml.
        /// </summary>
        [TestMethod]
        public void ReadingEnumColumnMemberListFromXml()
        {
            // Creating the enum column
            var xml = string.Format("<{0} {1}=\"{2}\">",
                EnumColumnDto.XmlTag,
                ColumnDto.NameAttribute,
                StringProperty.RandomIdentifier());

            // Creating the enumeration member list
            xml += string.Format("<{0}><{1} {2}=\"{3}\" /><{4} {5}=\"{6}\" /></{7}></{8}>",
                EnumColumnDto.MemberListAttribute,
                EnumMemberDto.XmlTag,
                EnumMemberDto.ValueAttribute,
                1,
                EnumMemberDto.XmlTag,
                EnumMemberDto.ValueAttribute,
                2,
                EnumColumnDto.MemberListAttribute,
                EnumColumnDto.XmlTag);

            var stream = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(xml)));

            var enumColumnDto = new EnumColumnDto();

            enumColumnDto.ReadXml(stream);

            Assert.AreEqual(enumColumnDto.Members.Count(), 2);
        }


        /// <summary>
        ///   Reading an empty enumeration column member list from xml.
        /// </summary>
        [TestMethod]
        public void ReadingEmptyEnumColumnMemberListFromXml()
        {
            // Creating the enum column
            var xml = string.Format("<{0} {1}=\"{2}\">",
                EnumColumnDto.XmlTag,
                ColumnDto.NameAttribute,
                StringProperty.RandomIdentifier());

            // Creating the enumeration member list
            xml += string.Format("<{0} /></{1}>",
                EnumColumnDto.MemberListAttribute,
                EnumColumnDto.XmlTag);

            var stream = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(xml)));

            var enumColumnDto = new EnumColumnDto();

            enumColumnDto.ReadXml(stream);

            Assert.AreEqual(enumColumnDto.Members.Count(), 0);
        }


        /// <summary>
        ///   Writing and reading the enumeration column member list.
        /// </summary>
        [TestMethod]
        public void WritingAndReadingMemberList()
        {
            var enumColumnDto = new EnumColumnDto
            {
                Name = "enum_column"
            };

            enumColumnDto.AddMember(new EnumMemberDto
            {
                Value = 1
            });
            enumColumnDto.AddMember(new EnumMemberDto
            {
                Value = 2,
                DisplayName = "The display name"
            });

            var memoryStream = new MemoryStream();
            var writer = new XmlTextWriter(memoryStream, Encoding.UTF8);

            enumColumnDto.WriteXml(writer);

            writer.Flush();

            memoryStream.Position = 0;
            var streamReader = new StreamReader(memoryStream);
            var xml = streamReader.ReadToEnd();

            Assert.IsFalse(string.IsNullOrEmpty(xml));

            memoryStream.Position = 0;
            var reader = new XmlTextReader(memoryStream);

            var readEnumColumnDto = new EnumColumnDto();

            readEnumColumnDto.ReadXml(reader);

            Assert.AreEqual(readEnumColumnDto.Members.Count(), 2);
        }
    }
}
